<template>
  <div class="viewContain">
    <el-form :model="listQuery" size="small" label-width="100px">
      <el-row>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 5 }" :xl="{ span: 5 }">
          <el-form-item label="采购单号 :">
            <el-input
              v-model="listQuery.purchaseNum"
              placeholder="请输入"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 10 }" :xl="{ span: 10 }">
          <el-form-item>
            <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
            <el-button size="mini" type="primary" @click="handleReload">重置</el-button>
            <el-button size="mini" type="primary" @click="handleBack">返回</el-button>
            <el-button v-if="isAdminRole !=='1'" size="mini" type="primary" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      width="1000px"
      @close="closeDialog"
    >
      <div class="refundInfo">
        <div>当前站点 : {{ orgName }}</div>
        <div><el-button size="mini" type="primary" @click="handleAddRefundItem">新增</el-button></div>
      </div>
      <el-form ref="formData" :model="formData" size="small" label-width="100px">
        <div class="refundTable">
          <el-table
            ref="table"
            v-loading="loading"
            fit
            stripe
            :data="tableDataRefund"
            border
            size="mini"
            style="margin-bottom:20px"
          >
            <el-table-column align="center" label="序号" type="index" width="50">
              <template slot-scope="scope">
                <span>{{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="productCode" align="center" label="商品信息">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.productCode"
                  placeholder="请选择"
                  filterable
                  clearable
                  style="width:100%"
                  @change="selectModel($event)"
                  @clear="clearTableRow(scope.$index)"
                >
                  <el-option
                    v-for="item in goodList"
                    :key="item.code"
                    :label="item.label + '(' + item.code + ')'"
                    :value="item.code"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="productNum" align="center" label="商品数量" width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.productNum" />
              </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="50">
              <template slot-scope="scope">
                <el-button class="text-button el-button--danger" size="mini" @click="handleDeleteItem(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-form-item label="备注 :" prop="remarks">
          <el-input v-model="formData.remarks" clearable type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item>
          <div style="text-align:right">
            <el-button size="mini" type="primary" plain @click="handleClose">取消</el-button>
            <el-button size="mini" type="primary" @click="handleSubmit">提交</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-table
      ref="table"
      v-loading="loading"
      fit
      stripe
      :data="tableData"
      border
      size="mini"
    >
      <el-table-column align="center" label="序号" type="index" width="50">
        <template slot-scope="scope">
          <span>{{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="purchaseNum" align="center" label="采购单号" />
      <el-table-column prop="createTime" align="center" label="提交日期" />
      <el-table-column align="center" label="操作" width="250">
        <template slot-scope="scope">
          <el-button class="text-button" size="mini" @click="handleDetail(scope.row.purchaseNum)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total-count="totalCount"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { commonMixin } from '@v/mixin/commonMixin.js'
import ComApiUrl from '@a/comomApi.js'
import pagination from '@/components/pagination/index.vue'
import { queryProductListPurchase } from '@a/business/site.js'
export default {
  components: { pagination },
  mixins: [commonMixin],
  data() {
    return {
      comApiUrlList: new ComApiUrl('/member/api/purchase/queryIntentionBySite'),
      comApiUrlAdd: new ComApiUrl('/member/api/purchase/addPurchaseIntention'),
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        orgId: ''
      },
      tableData: [],
      orgName: '', // 站点名称
      dialogFormVisible: false,
      dialogTitle: '采购单',
      tableDataRefund: [{}],
      goodList: [],
      formData: {
        list: [], // 商品集合
        // orgId: '', //  机构id
        remarks: ''
        // returnNum: ''
      },
      selectValue: [],
      isAdminRole: '',
      rule: true
    }
  },
  mounted() {
    this.comomFun()
  },
  methods: {
    comomFun() {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      this.orgName = userInfo.orgName
      this.isAdminRole = userInfo.isAdminRole
      const { isAdminRole, orgId } = userInfo
      const id = this.$route.params.id
      isAdminRole === '1' ? this.listQuery.orgId = id : this.listQuery.orgId = orgId
      isAdminRole === '1' ? this.formData.orgId = id : this.formData.orgId = orgId
      this.getList()
    },
    handleReload() {
      this.listQuery = {
        pageNo: 1,
        pageSize: 10
      }
      this.comomFun()
    },
    // 详情
    handleDetail(purchaseNum) {
      this.$router.push('/business/address/purchase/detail/' + purchaseNum)
    },
    // 新增
    handleAdd() {
      this.dialogFormVisible = true
      // 商品列表下拉框
      this.tableDataRefund = [{}]
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      const { userId, orgId } = userInfo
      queryProductListPurchase({ id: userId, orgId }).then(res => {
        if (res.code === 0) {
          this.goodList = res.data
          // console.log(this.goodList)
        } else {
          this.message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 新增采购单
    handleAddRefundItem() {
      this.tableDataRefund.push({})
    },
    // 删除采购单条例
    handleDeleteItem(index) {
      this.tableDataRefund.splice(index, 1)
      this.selectValue.splice(index, 1)
    },
    selectModel(code) {
      this.goodList.find((item) => {
        if (item.code === code) {
          this.selectValue.push({ productName: item.label })
        }
      })
      console.log(this.selectValue)
    },
    clearTableRow(index) {
    },
    // 提交采购单
    handleSubmit() {
      // 合并两个数组对象成一个新对象
      this.tableDataRefund = this.tableDataRefund.map((item, index) => {
        return { ...item, ...this.selectValue[index] }
      })
      console.log(this.tableDataRefund)
      this.formData.list = this.tableDataRefund
      // console.log(this.formData.list)
      for (var i = 0; i < this.formData.list.length; i++) {
        if (!this.formData.list[i].productNum) {
          this.$message({
            type: 'warning',
            message: '商品采购数量不能为空!'
          })
          this.rule = false
          break
        } else {
          const reg = new RegExp(/^[0-9]*[1-9][0-9]*$/) // 商品数量要是大于0的正整数
          const flag = reg.test(this.formData.list[i].productNum)
          if (!flag) {
            this.$message({
              type: 'warning',
              message: '商品数量为大于0的正整数!'
            })
            this.rule = false
            break
          } else {
            this.rule = true
          }
        }
        if (!this.formData.list[i].productName || !this.formData.list[i].productCode) {
          this.$message({
            type: 'warning',
            message: '请选择商品!'
          })
          this.rule = false
          break
        } else {
          this.rule = true
        }
      }
      // 判断重复的商品
      const productCodes = this.formData.list.map(item => item.productCode)
      console.log(productCodes)
      const productCodesSet = new Set(productCodes)
      if (productCodesSet.size === productCodes.length) {
        console.log('不存在同个值')
      } else {
        this.$message({
          type: 'warning',
          message: '该商品已经在采购单中!'
        })
        this.rule = false
      }
      // console.log(this.formData)
      console.log(this.rule)
      this.rule ? this.create() : ''
      // this.$refs.formData.validate(valide => {
      //   valide ? this.create() : ''
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
.refundInfo {
  width: 100%;
  height: 50px;
  line-height: 50px;
  display: flex;
  justify-content:space-between;
}
.refundTable {
  width: 100%;
  height: 250px;
  overflow: auto;
}
</style>
